<template>
  <BaseForm v-model="formDataModel" @close="$emit('callBack')" />
</template>

<script lang="tsx" setup>
import type { FormInstance } from 'element-plus'
import SupplierInfoApi from '/@/api/webPath/SupplierInfoApi.ts';
import { translate } from "/@/i18n";
import FORM_FIELD_TYPE from "/@/constants/FormFieldType.ts";
import SupplierInfoBaseApi from '~/src/api/webPath/SupplierInfoBaseApi';
import SupplierInfoTypeApi from '~/src/api/webPath/SupplierInfoTypeApi';
defineOptions({
  name: 'SupplierInfoEdit',
})
const props = defineProps({
  modelValue: {

  }
})
const emit = defineEmits(['fetch-data', 'callBack'])

const formRef = ref<FormInstance>();
const title = ref<string>('');
const dialogFormVisible = ref<boolean>(false);
const supplierList = ref()
const supplierTypeList = ref()


onMounted(async () => {
  const data = (await SupplierInfoTypeApi.getSupplierTypeList()).data
  console.log("data:", data)
  // 详情页返回的供应商id位数值型，需强制转换，否则匹配不上
  supplierTypeList.value = data.map(item => ({ label: item.name, value: +item.id }))
  console.log("supplierTypeList", supplierTypeList.value)
  // data.map(x=>{label:data})
})

async function remoteSearch(query: string) {
  // TODO 更换为全量搜索基础供应商列表
  const data = (await SupplierInfoBaseApi.getPageData({ supplierName: query })).data.records
  console.log("search data:", data);
  supplierList.value = data
  const options = data.map(item => ({
    label: item.supplierName,
    value: item.id
  }))
  console.log("options", options)
  return options
}

function updateForm(id: any, updateParam: (key: any, value: any) => void) {
  console.log("update ids:", id)
  console.log("param", updateParam)
  const supplier = supplierList.value.find(x => x.id === id)
  console.log("current supplier", supplier)

  for (const key of Object.keys(toRaw(supplier))) {
    for (const { field } of formDataModel.value.items) {
      if (key === field) {
        updateParam(key, supplier[key])
      }
    }
  }
}

const bussinessFormItemList = [

  {
    label: "供应商许可证编码",
    field: "produceCode",
    clearable: true,
    type: FORM_FIELD_TYPE.INPUT,

    placeholder: "请输入",

    rule: [{
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },
    {
      required: true,
      message: "请填写供应商许可证编码"
    }
    ],

  },
  {
    label: "供应商许可证发证日期",
    field: "produceSignDate",
    clearable: true,
    type: FORM_FIELD_TYPE.DATE,

    placeholder: "请输入",

    rule: {
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },

  },

  {
    label: "供应商许可有效期",
    field: "produceEffectiveDate",
    clearable: true,
    type: FORM_FIELD_TYPE.DATE,
    placeholder: "请输入",

    rule: [{
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },
    {
      required: true,
      message: "请填写供应商许可有效期"
    }
    ],
    config: {
      props: {   //日期精度配置
        type: "daterange",
        startPlaceholder: "开始日期",
        endPlaceholder: "结束日期",
        format: "YYYY-MM-DD",
      }
    },
  },
  {
    label: "供应商许可证经营项目",
    field: "produceTypeName",
    clearable: true,
    type: FORM_FIELD_TYPE.TEXTAREA,

    placeholder: "请输入",

    rule: {
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },

  },
  {
    label: "供应商产品类型",
    field: "produceClass",
    clearable: true,
    type: FORM_FIELD_TYPE.TEXTAREA,

    placeholder: "请输入",

    rule: {
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },

  },
  {
    label: "供应商类型编码",
    field: "produceClassCode",
    clearable: true,
    type: FORM_FIELD_TYPE.TEXTAREA,

    placeholder: "请输入",

    rule: {
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },

  },
  {
    label: "供应商类别名称",
    field: "produceClassName",
    clearable: true,
    type: FORM_FIELD_TYPE.TEXTAREA,

    placeholder: "请输入",

    rule: {
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },

  },
  // {
  //   label: "供应商类别名称",
  //   field: "produceClassName",
  //   clearable: true,
  //   type: FORM_FIELD_TYPE.TEXTAREA,

  //   placeholder: "请输入",

  //   rule: {
  //     trigger: 'blur',
  //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
  //       callback();
  //     },
  //   },

  // },
  // {
  //   label: "供应商类型编码",
  //   field: "produceCode",
  //   clearable: true,
  //   type: FORM_FIELD_TYPE.TEXTAREA,

  //   placeholder: "请输入",

  //   rule: {
  //     trigger: 'blur',
  //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
  //       callback();
  //     },
  //   },

  // },
  {
    label: "供应商品种明细",
    field: "produceClassDetail",
    clearable: true,
    type: FORM_FIELD_TYPE.TEXTAREA,

    placeholder: "请输入",

    rule: [{
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {  //绑定验证
        callback();
      },
    },
    {
      required: true,
      message: "请填写供应商品种明细"
    }
    ],

  },
  {
    label: "供应商许可证",
    field: "produceUrl",
    clearable: true,
    type: FORM_FIELD_TYPE.UPLOAD,
    config: {
      limit: 1
    },
    placeholder: "请输入",
    rule: {
      trigger: 'blur',
      message: '许可证不能为空'
    },
  },
]

const licenseType = ref()

// 监听选择或者编辑获取到的许可证类型动态生成对应的输入项目
// watch(() => licenseType.value, (v) => {
//   // 经营许可证
//   const fixedItems = formDataModel.value.items.filter(x => x.fixed)
//   console.log("current value", v, typeof v)
//   console.log("licenseType value", licenseType.value)
//   if (v === '经营许可证' || v === '生产许可证') {
//     formDataModel.value.items = [...fixedItems, ...bussinessFormItemList]
//   } else {
//     formDataModel.value.items = fixedItems;
//   }
// })
const formDataModel = ref({
  columnCount: 1,
  expandLimit: 6,
  autoFit: false,
  columnWidth: '300px',
  labelPosition: 'right',
  labelWidth: '230px',
  modelData: {},  //表单参数值 初始化
  callback: async (any: object) => {  //表单执行成功后回调
    //完成数据提交
    console.log("received data:", any)
    for (const item of formDataModel.value.items) {
      if (item.multiple === true) {
        any[item.field] = any[item.field].join()
      }
    }
    const { message } = await SupplierInfoApi.save(any)
    $baseMessage(message, 'success', 'vab-hey-message-success');
    dialogFormVisible.value = false

    //事件及数据推送到上一层父类
    emit('callBack', any); //把表单数据推送到上一层
  },
  items: [  //表单item数据初始化

    {
      label: "供应商类型",
      field: "supplierType",
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
      options: supplierTypeList,
      // type: FORM_FIELD_TYPE.INPUT,
      // multiple: true,
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请选择供应商类型"
      }
      ],

    },
    {
      label: "供应商名称",
      field: "supplierName",
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,

      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请填写供应商名称"
      }
      ],

    },
    // {
    //   label: "供应商名称",
    //   field: "supplierName",
    //   fixed: true,
    //   labelField: true,
    //   clearable: true,
    //   type: FORM_FIELD_TYPE.INPUT,
    //   // type: FORM_FIELD_TYPE.INPUT,
    //   // render({ handlers }) {
    //   //   return <RemoteSearchSelect placeholder="请输入供应商名称" remoteSearch={remoteSearch} onUpdate={(id) => updateForm(id, handlers.updateParam)} />
    //   // },

    //   placeholder: "请输入",
    //   rule: [
    //     {
    //       trigger: 'blur',
    //       validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //         callback();
    //       },
    //     },
    //     {
    //       required: true,
    //       message: "请填写供应商名称"
    //     }
    //   ]
    // },
    {
      label: "供应商地址",
      field: "supplierAdd",
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,

      placeholder: "请输入",

      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },

    },

    {
      label: "营业执照",
      field: "creditUrl",
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.UPLOAD,
      config: {
        limit: 1
      },
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        message: '营业执照不能为空'
      },
    },
    {
      label: "供应商营业执照统一社会信用代码",
      fixed: true,
      field: "creditCode",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,

      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请填写供应商营业执照统一社会代码"
      }
      ],

    },
    {
      label: "供应商营业执照发证日期",
      fixed: true,
      field: "creditSignDate",
      clearable: true,
      type: FORM_FIELD_TYPE.DATE,
      placeholder: "请输入",

      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },

      config: {
        props: {   //日期精度配置
          type: "daterange",
          startPlaceholder: "开始日期",
          endPlaceholder: "结束日期",
          format: "YYYY-MM-DD",
        }
      },
    },


    {
      label: "供应商许可证类型",
      field: "licenseType",
      // noSend: true,
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
      options: [
        {
          value: '无许可证',
          label: "无许可证"
        },
        {
          value: '经营许可证',
          label: "经营许可证"
        },
        {
          value: '生产许可证',
          label: "生产许可证"
        },

      ],
      callback(handlers: any, v: any) {
        console.log("callback 111", v)
        licenseType.value = v
        console.log(123456, licenseType.value);
        const fixedItems = formDataModel.value.items.filter(x => x.fixed);

        if (licenseType.value === '无许可证') {
          // 如果选择“无许可证”，则将 bussinessFormItemList 中的数据清空
          formDataModel.value.items = fixedItems;
        } else if (licenseType.value === '经营许可证' || licenseType.value === '生产许可证') {
          formDataModel.value.items = [...fixedItems, ...bussinessFormItemList];
        } else {
          formDataModel.value.items = fixedItems;
        }
      },
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请选择供应商许可类型"
      }
      ],

    },

  ],
  // buttons: [
  //   {
  //     name: "导出",
  //     buttonClass: 'primary',
  //     width: 100,
  //     click: ({ row, handlers }) => {   //暴露的方法钩子
  //       SupplierInfoApi.pageDataXls(handlers.getRequestParams(), handlers.getXlsTitle())
  //     }
  //   },
  // ]
})






//页面数据加载
onMounted(async () => {

  //初始化数据model
  if (props.modelValue.query) { //跳转过来时候有参数
    if (props.modelValue.query.supplierInfoId) {  //id存在则为编辑，加载网络数据，如上级页面带参数手动覆盖

      const res = await SupplierInfoApi.getDetail({
        supplierInfoId: props.modelValue.query.supplierInfoId   //从路由中获取参数
      })
      if (res) {
        const { data } = res
        formDataModel.value.modelData = data;
        licenseType.value = data.licenseType;
        const fixedItems = formDataModel.value.items.filter(x => x.fixed);
        if (licenseType.value === '经营许可证' || licenseType.value === '生产许可证') {
          formDataModel.value.items = [...fixedItems, ...bussinessFormItemList];
        } else {
          formDataModel.value.items = fixedItems;
        }
      }

      console.log("licenseType value", licenseType.value)
    } else {
      //新增时候则用父类页面传参默认填充可根据业务修改
      for (const key in props.modelValue.query) {
        formDataModel.value.modelData[key] = props.modelValue.query[key]
      }
    }
  }
  // watchEffect(() => {

  // });
})


//方法暴露区域  todo
defineExpose({

})

</script>
